<script setup lang="ts">
  import { PropType } from 'vue'
  import { DateTimeType, CustomFormFieldVal } from '../../hooks/types'

  const props = defineProps({
    datetimeType: {
      type: String as PropType<DateTimeType>,
      default: () => 'date',
    },
    placeholder: {
      type: String,
      default: () => '请选择日期时间',
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
    startOnlyToday: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (e: 'change', value: CustomFormFieldVal['datetimeVal']): void
  }>()

  // 绑定的值
  const value = defineModel<CustomFormFieldVal['datetimeVal']>('modelValue', {
    default: {
      date: '',
      dateTime: '',
      time: '',
      timeRange: {
        date: '',
        startTime: '',
        endTime: '',
      },
    },
  })

  /**
   * 日期、日期时间、时间选择事件
   */
  const handleChange = () => {
    emits('change', value.value)
  }
</script>

<template>
  <div class="custom-date-time">
    <el-date-picker
      v-if="props.datetimeType === 'date'"
      v-model="value.date"
      :placeholder="props.placeholder"
      :disabled="props.disabled"
      format="YYYY-MM-DD"
      value-format="YYYY-MM-DD"
      @change="handleChange"
    />

    <el-date-picker
      v-if="props.datetimeType === 'date-time'"
      v-model="value.dateTime"
      type="datetime"
      :placeholder="props.placeholder"
      :disabled="props.disabled"
    />

    <el-time-picker
      v-if="props.datetimeType === 'time'"
      v-model="value.time"
      :placeholder="props.placeholder"
      :disabled="props.disabled"
    />

    <template v-if="props.datetimeType === 'time-range'">
      <el-date-picker
        v-model="value.timeRange.date"
        :placeholder="props.placeholder"
        :disabled="props.disabled"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        :disabled-date="props.startOnlyToday ? (time: Date) => time.getTime() < Date.now() - 8.64e7 : () => false"
      />
      <el-time-select
        v-model="value.timeRange.startTime"
        :placeholder="props.placeholder"
        :disabled="props.disabled"
        :max-time="value.timeRange.endTime"
        start="06:00"
        end="24:00"
      />
      <el-time-select
        v-model="value.timeRange.endTime"
        :placeholder="props.placeholder"
        :disabled="props.disabled"
        :min-time="value.timeRange.startTime"
        start="06:00"
        end="24:00"
      />
    </template>
  </div>
</template>

<style scoped lang="scss">
  .custom-date-time {
    width: 100%;
    display: flex;
    column-gap: 4px;

    :deep(.el-input) {
      height: 28px;
      width: 100%;

      .el-input__wrapper {
        box-sizing: border-box;
      }
    }
  }
</style>
